package org.lessnote.server.controller;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.URLUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.lboot.core.domain.ResponseDTO;
import org.lboot.core.exception.BusinessException;
import org.lessnote.server.params.NoteFileParams;
import org.lessnote.server.service.NoteCtl;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

/**
 * @author kindear
 * 笔记文件管理
 */
@Slf4j
@RestController
@RequestMapping("note")
@Api(tags = "笔记文件")
@AllArgsConstructor
public class NoteFileController {
    NoteCtl noteCtl;

    @PostMapping("upload")
    @ApiOperation(value = "文件上传")
    @SneakyThrows
    public ResponseDTO<Object> fileUpload(NoteFileParams params) {
        // 校验路径参数
        String fullPath = params.getFullPath();
        if (fullPath.startsWith("/")){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"不可以使用 / 开头");
        }
        String ext = FileNameUtil.extName(fullPath);
        if (Validator.isEmpty(ext)){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"文件必须指定后缀");
        }
        return ResponseDTO.succData(
                noteCtl.uploadFile(params)
        );
    }

    @GetMapping("files")
    @ApiOperation(value = "文件列表")
    public ResponseDTO<Object> listDirFiles(@RequestParam("dir") String dir){
        String fullPath = URLUtil.decode(dir);
        if (fullPath.startsWith("/")){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"不可以使用 / 开头");
        }
        return ResponseDTO.succData(
                noteCtl.listFiles(fullPath)
        );
    }
}
